package com.jbt.mds.obdsdk

import android.app.AlertDialog
import android.app.Dialog
import android.app.ProgressDialog
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.OnClickListener
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.RadioGroup.OnCheckedChangeListener
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import android.widget.AdapterView
import androidx.annotation.RequiresApi
import androidx.databinding.DataBindingUtil
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.databinding.ObservableList
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSON
import com.bumptech.glide.Glide
import com.github.chrisbanes.photoview.PhotoView
import com.github.dhaval2404.imagepicker.ImagePicker
import com.google.gson.Gson
import com.jbt.mds.obdsdk.HttpUtil.Companion.BASE_URL
import com.jbt.mds.obdsdk.dialog.CarInfoViewModel
import com.jbt.mds.obdsdk.dialog.InfoViewModel121
import com.jbt.mds.obdsdk.dialog.InfoViewModel122
import com.jbt.mds.obdsdk.dialog.InfoViewModel211
import com.jbt.mds.obdsdk.dialog.ItemLineModel
import com.jbt.mds.obdsdk.extension.SPUtils
import com.jbt.mds.sdk.model.DataStreamInfo
import com.jbt.mds.sdk.obd.ObdResource
import com.jbt.mds.sdk.obd.VciFirmwareResource
import com.jbt.mds.sdk.okhttp.model.Progress
import com.jbt.mds.sdk.okhttp.request.HttpRespondCode
import com.jbt.mds.sdk.vin.VinUtils
import com.zhy.http.okhttp.callback.StringCallback
import me.tatarka.bindingcollectionadapter2.itembindings.OnItemBindClass
import me.tatarka.bindingcollectionadapter2.map
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.lang.Exception
import java.util.concurrent.TimeUnit


class HomeFragment: Fragment()   {
    private val TAG = "Obdljzt"
    private var gb = "国3"
    private var etVehicleType = "大型车辆"
    lateinit var rView: View
    var uploadImageList: ArrayList<String> = ArrayList()
    lateinit var adapter: ImagePickerAdapter
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?  {
        super.onCreate(savedInstanceState)
        rView = View.inflate(context, R.layout.fg_home, null)

        // 检查是否需要显示数据读取提示
        checkAndShowDataReadingDialog()

        return rView
    }
    
    override fun onResume() {
        super.onResume()
        // 只有从更新页面返回时才重新检查更新状态
        if (updateCheckComplete && isFromUpdatePage) {
            Log.i(TAG, "从更新页面返回，验证更新是否完成")
            resetUpdateStatus()
            verifyUpdateCompletion()
        }
    }
    
    override fun onPause() {
        super.onPause()
        // 页面暂停时，停止数据检查
        stopDataCheck()
    }

    override fun onDestroyView() {
        println("销毁")
        super.onDestroyView()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        //adapter与 数据的加载

        initListener()
        initData()//


    }

    private fun initData() {

    }



    val items: ObservableList<Any>  = ObservableArrayList<Any>()
    val rvItems = OnItemBindClass<Any>().apply {
        map<ItemLineModel>(BR.viewModel, R.layout.qb_item_line)
        map<InfoViewModel211>(BR.viewModel, R.layout.three_text_info_layout)
        map<InfoViewModel121>(BR.viewModel, R.layout.three_text_info_layout121)
        map<InfoViewModel122>(BR.viewModel, R.layout.three_text_info_layout122)
    }


    val realTimeItems: ObservableList<Any>  = ObservableArrayList<Any>()

    val realTimeItemsForTenSecond = ObservableArrayList<InfoViewModel211>()

    public fun updateDataStream(dataStreamInfo: DataStreamInfo) {

        val item = realTimeItems.filterIsInstance<InfoViewModel211>().find { it.id.equals(dataStreamInfo.strID) }
        val viewModel = InfoViewModel211(dataStreamInfo.strID,ObservableField(dataStreamInfo.strCaption),ObservableField(dataStreamInfo.strValue),ObservableField(dataStreamInfo.strUnit))

        realTimeItemsForTenSecond.add(viewModel)

        if(item!=null){
            item.middleText.set(dataStreamInfo.strValue)
        }else{
            realTimeItems.add(ItemLineModel())
            realTimeItems.add(viewModel)
        }

        filterData()
        
        // 如果有数据流更新且正在显示数据读取提示，检查是否可以隐藏
        if (isDataReading && realTimeItems.isNotEmpty()) {
            // 延迟一点时间再检查，确保数据完全加载
            Handler(Looper.getMainLooper()).postDelayed({
                if (realTimeItems.isNotEmpty() && isDataReading) {
                    hideDataReadingDialog()
                    Toast.makeText(requireContext(), "数据流读取完成", Toast.LENGTH_SHORT).show()
                }
            }, 1000) // 延迟1秒检查
        }
    }

    private fun filterData() {
        val currentTimeMillis = System.currentTimeMillis();
//        println(realTimeItemsForTenSecond+33);

        val filter = realTimeItemsForTenSecond.filter { currentTimeMillis - it.time < 60*1000 }
        realTimeItemsForTenSecond.clear()
        realTimeItemsForTenSecond.addAll(filter)
    }



    private fun sendValidationRequest(number: String, color: String, type: String, vin: String, emissionStandard: String, dialog:Dialog) {
        var progressDialog = ProgressDialog(activity)
        progressDialog.setTitle("正在提交")
        progressDialog.setMessage("请稍后")
        progressDialog.setCancelable(false)
        progressDialog.show()

        println(uploadImageList+"uploadImageList")
        var obdDetector = Singleton.getObdDetector()
        val ecuInfos= obdDetector.ecuInfo
        val systemCheckState: List<DataStreamInfo> = obdDetector.systemCheckState  //获取获取系统检测状态(就绪状态)
        filterData()
        val client = OkHttpClient.Builder()
            .callTimeout(1,TimeUnit.DAYS)
            .readTimeout(1,TimeUnit.DAYS)
            .writeTimeout(1,TimeUnit.DAYS)
            .build()

        // 构造 JSON 数据
        val json = """{"number":"$number","color":"$color","gb":"$gb","type":"$type","vin":"$vin","emissionStandard":"$emissionStandard",
            |"dataList":${Gson().toJson(realTimeItemsForTenSecond)},"ecu":${Gson().toJson(ecuInfos)},"systemCheckState":${Gson().toJson(systemCheckState)},
            | "images": ${Gson().toJson(uploadImageList)}}""".trimMargin()

        uploadImageList.clear()

        val body = RequestBody.create("application/json; charset=utf-8".toMediaType(), json)

        Log.i("11110","token "+SPUtils.getString("token",""))

        // 构建 POST 请求
        val request = Request.Builder()
            .url("http://115.153.96.26:10061/api")
            .post(body)
            .addHeader("Authorization","Bearer "+SPUtils.getString("token",""))
            .build()

        // 异步发送请求
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {

                activity?.runOnUiThread {
                    progressDialog.dismiss()
                    dialog.dismiss()
                    Toast.makeText(activity, "请求失败: ${e.message}", Toast.LENGTH_LONG).show()
                }

            }

            override fun onResponse(call: Call, response: Response) {
                val responseBody = response.body?.string() ?: "无响应内容"
                activity?.runOnUiThread {
                    progressDialog.dismiss()
                    dialog.dismiss()
                    if (response.isSuccessful) {
                                val json = JSONObject(responseBody)
                                if(json.optInt("code",-1) ==200){

                                    val data = json.optString("data")
                                    if (!TextUtils.isEmpty(data)) {
                                        val dataMap = Gson().fromJson<Map<String, Map<String, Any>>>(data.toString(), Map::class.java)

                                        items.clear()
                                        dataMap.forEach { (key, valueMap) ->
                                            val msg = valueMap["msg"] ?: key
                                            val  codeObj =valueMap["code"] ?: key
                                            val code = when (codeObj) {
                                                null -> -1
                                                is Number -> codeObj.toInt() // Double、Int、Float 等都属于 Number
                                                is String -> codeObj.toIntOrNull() ?: -1
                                                else -> -1
                                            }
                                            items.add(ItemLineModel())
                                            if(code == 0){
                                                items.add(InfoViewModel122("",
                                                    ObservableField("问题"), ObservableField(key), ObservableField(msg.toString())))
                                            }

                                        }
                                        items.add(ItemLineModel())
                                        showCustomDialog(items,"校验结果")

                                    }else{
                                        Toast.makeText(activity, "校验成功", Toast.LENGTH_LONG).show()
                                    }

                                }else{
                                    println("${response}da")
                                    Toast.makeText(activity, "校验失败: ${json.optInt("code",-1)}", Toast.LENGTH_LONG).show()
                                }


                    } else {
                        println("${response}da1")
                        Toast.makeText(activity, "校验失败: ${response.code}", Toast.LENGTH_LONG).show()
                    }
                }

            }
        })
    }

    private fun initListener() {
        adapter = ImagePickerAdapter(requireActivity(), 9)
        adapter.setOnItemClickListener(object :
            ImagePickerAdapter.OnRecyclerViewItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                when(position) {
                    -1 -> {
                        ImagePicker.with(requireActivity())
                            .cameraOnly()	//User can only capture image using Camera
                            .start(CAMERA_IMAGE_REQ_CODE)
                    }
                    else -> {
                        previewImage(adapter.getImages()[position])
                    }
                }
            }
        })
        
        // 设置拍照完成监听器
        adapter.setOnPhotoTakenListener(object : ImagePickerAdapter.OnPhotoTakenListener {
            override fun onPhotoTaken(uri: Uri) {
                // 拍照完成后不立即提示，等上传成功后再提示
                Log.i(TAG, "拍照完成，开始上传: $uri")
                // 可以在这里做：
                // - 更新UI
                // - 记录拍照历史
                // - 其他处理逻辑
            }
        })

        rView.findViewById<View>(R.id.checkobd).setOnClickListener {

            if(realTimeItems.isEmpty()){
                Toast.makeText(view!!.context, "暂无数据", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            var obdDetector1 = Singleton.getObdDetector()
//            var ddd= obdDetector1.vin
            val cleanedDdd = obdDetector1.vin?.trim().orEmpty()//判断返回的vin码是不是为空，为空可能传很多空格
            val rootView = LayoutInflater.from(activity).inflate(R.layout.input_dialog,null)
            val dialog = Dialog(requireContext())
            dialog.setContentView(rootView)
            dialog.window?.setLayout(
                WindowManager.LayoutParams.MATCH_PARENT, // 宽度占满屏幕
                WindowManager.LayoutParams.WRAP_CONTENT // 高度根据内容自适应
            )
            dialog.show()

            // 设置关闭监听器
            dialog.setOnDismissListener {
                // ✅ 弹窗关闭后执行这里
                Toast.makeText(context, "弹窗已关闭", Toast.LENGTH_SHORT).show()
                uploadImageList.clear();
                adapter.clearImages(); // 清空拍照历史
                println(uploadImageList+"uploadImageList");
                // 可以在这里做：
                // - 刷新页面
                // - 释放资源
                // - 回调通知
            }

            val btnValidate = rootView.findViewById<Button>(R.id.btn_validate)
            val imageListView = rootView.findViewById<RecyclerView>(R.id.image_list_view);

            imageListView.adapter = adapter

            val inconsistentButton = rootView.findViewById<RadioButton>(R.id.rb_inconsistent)
                if (inconsistentButton.isChecked) {
                    imageListView.visibility = VISIBLE
                } else {
                    imageListView.visibility = GONE
                }
                inconsistentButton.setOnCheckedChangeListener { p0, checked ->
                    if (checked) {
                        imageListView.visibility = VISIBLE
                    } else {
                        imageListView.visibility = GONE
                    }
                }

            val etVehicleVinView = rootView.findViewById<EditText>(R.id.et_vehicle_vin)
            val addxc = rootView.findViewById<RadioGroup>(R.id.rg_vehicle_color)
            var colortye="蓝色"
            addxc.setOnCheckedChangeListener { group, checkedId ->
                when (checkedId) {
                    R.id.rb_blue -> {
                        // 选择了蓝色
                        println("选中：蓝色")
                        colortye="蓝色"
                    }
                    R.id.rb_yellow -> {
                        // 选择了黄色
                        println("选中：黄色")
                        colortye="黄色"
                    }
                }
            }

            // 设置排放标准下拉框
            val spinnerEmissionStandard = rootView.findViewById<Spinner>(R.id.spinner_emission_standard)
            val ctype: MutableList<String> = mutableListOf("国2","国3", "国4", "国5","国6")
            val spinnerAdapter = ArrayAdapter<String>(requireContext(), android.R.layout.simple_spinner_item, ctype)
            spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            spinnerEmissionStandard.adapter = spinnerAdapter
            
            var selectedEmissionStandard = "国3" // 默认选择国1
            spinnerEmissionStandard.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                    selectedEmissionStandard = ctype[position]
                    gb=selectedEmissionStandard;
                    println("选中排放标准：$selectedEmissionStandard")
                }
                
                override fun onNothingSelected(parent: AdapterView<*>?) {
                    // 不做任何处理
                }
            })


            // 设置车辆类型下拉框
            val spinnerEmissionScllx= rootView.findViewById<Spinner>(R.id.spinner_emission_cllx)
            val cllx1: MutableList<String> = mutableListOf("大型汽油车","大型柴油车", "其他")
            val spinnerAdapter1 = ArrayAdapter<String>(requireContext(), android.R.layout.simple_spinner_item, cllx1)
            spinnerAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            spinnerEmissionScllx.adapter = spinnerAdapter1

            var selectedEmissionScllx = "大型汽油车" // 默认选择大型汽油车
            spinnerEmissionScllx.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                    selectedEmissionScllx = cllx1[position]
                    etVehicleType=selectedEmissionScllx;
                    println("选中排放标准：$selectedEmissionScllx")
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                    // 不做任何处理
                }
            })



            etVehicleVinView.setText(cleanedDdd)
            btnValidate.setOnClickListener {
                val etVehicleNumber = rootView.findViewById<EditText>(R.id.et_vehicle_number).text.toString().trim()
//                val etVehicleColor = rootView.findViewById<EditText>(R.id.et_vehicle_color).text.toString().trim()
//                val etVehicleType = rootView.findViewById<EditText>(R.id.et_vehicle_type).text.toString().trim()
                val etVehicleVin = etVehicleVinView.text.toString().trim() // 直接用已持有的引用

// 校验数据是否为空
                when {
                    etVehicleNumber.isEmpty() -> {
                        Toast.makeText(activity, "请输入车辆号码", Toast.LENGTH_LONG).show()
                    }
//                    etVehicleColor.isEmpty() -> {
//                        Toast.makeText(activity, "请输入车辆颜色", Toast.LENGTH_LONG).show()
//                    }
                    etVehicleType.isEmpty() -> {
                        Toast.makeText(activity, "请输入车辆类型", Toast.LENGTH_LONG).show()
                    }
                    etVehicleVin.isEmpty() -> {
                        Toast.makeText(activity, "请输入车辆 VIN 码", Toast.LENGTH_LONG).show()
                    }
                    else -> {
                        println(etVehicleNumber+"--"+colortye+"---"+etVehicleType+
                            "+++"+etVehicleVin+"222222222222222222")
                        // 所有输入框都不为空，发送请求
                        sendValidationRequest(etVehicleNumber, colortye, etVehicleType,
                            etVehicleVin, selectedEmissionStandard, dialog)
                    }
                }
            }
        }

        val ll_b1 = rView.findViewById<View>(R.id.ll_b1)
        val ll_b2 = rView.findViewById<View>(R.id.ll_b2)
        var b3= rView.findViewById<View>(R.id.vehicleInformation)


        rView.findViewById<View>(R.id.vehicleInformation).setOnClickListener {

            if (activity != null) {
                val boolean = (activity as MainActivity2).getCheckStatus()


                if(!boolean){
                    Toast.makeText(activity, "未初始化状态", Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }

                var obdDetector = Singleton.getObdDetector()
                val ecuInfos= obdDetector.ecuInfo



                items.clear()
                for (info in ecuInfos) {
                    Log.i("ECUdatalist", info.toString())
                    items.add(ItemLineModel())
                    items.add(InfoViewModel121("",ObservableField( info.strId),ObservableField(info.strCaption),ObservableField(info.strInformation)))
                }
                items.add(ItemLineModel())

                showCustomDialog(items,"车辆信息")

            }

        }
//        rView.findViewById<View>(R.id.v_x).setOnClickListener {
//            ll_b1.visibility = View.GONE
//            ll_b2.visibility = View.VISIBLE
//        }
//        rView.findViewById<View>(R.id.v_s).setOnClickListener {
//            ll_b1.visibility = View.VISIBLE
//            ll_b2.visibility = View.GONE
//        }我和你先说x
        rView.findViewById<View>(R.id.ll_sjl).setOnClickListener {
            // 使用旋转提示等待数据
            startDataCheck("数据流") {
                if (!realTimeItems.last().javaClass.name.equals("com.jbt.mds.obdsdk.dialog.InfoViewModel")) {
                    realTimeItems.add(ItemLineModel())
                }
                showCustomDialog(realTimeItems,"信息流")
            }
        }
//        rView.findViewById<View>(R.id.dqls).setOnClickListener {
//            val intent = Intent(requireContext(), DqlsActivity::class.java)
//            startActivity(intent)
//        }

        //{strLinkFile='null', id='1', faultCode='P062B', description='内部控制模块喷油嘴控制性能不良', status='1', type='0', dtcId='null', path='null', conditions='null', reasons='null', recommendations='null', imgParentPath='null', dtcCode='062B'}


        rView.findViewById<View>(R.id.realData).setOnClickListener {
            // 使用旋转提示等待数据
            startDataCheck("故障码") {
                val dtc = Singleton.getObdDetector().dtc
                items.clear()
                
                for (dtc1 in dtc) {
                    items.add(ItemLineModel())
                    items.add(InfoViewModel121("",ObservableField(dtc1.faultCode),ObservableField(dtc1.description),ObservableField(dtc1.dtcCode)))
                }
                items.add(ItemLineModel())

                showCustomDialog(items,"故障码")
            }
        }
    }
    private fun showCustomDialog(items: ObservableList<Any>,title:String){
        val dialog = Dialog(requireContext())

        val carInfoViewModel = CarInfoViewModel(items,rvItems)

        val contentView = DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(activity),R.layout.custom_dialog,null,false)
        contentView.setVariable(BR.viewModel,carInfoViewModel)
        dialog.setContentView(contentView.root)

        dialog.window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT, // 宽度占满屏幕
            WindowManager.LayoutParams.WRAP_CONTENT // 高度根据内容自适应
        )

        dialog.findViewById<TextView>(R.id.dialog_title).setText(title)



        val button: Button = dialog.findViewById(R.id.dialog_button)
//        val gridView: GridView = dialog.findViewById(R.id.grid)
//
//        val numbers = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
//        val adapter = NumberAdapter(requireContext(), numbers)
//        gridView.adapter = adapter

        button.setOnClickListener {
            dialog.dismiss() // 关闭弹窗
        }
        // 显示对话框
        dialog.show()
    }

    val httpUtil:HttpUtil = HttpUtil()
    
    // 旋转提示对话框相关变量
    private var loadingDialog: Dialog? = null
    private var dataCheckHandler: Handler? = null
    private var dataCheckRunnable: Runnable? = null
    private val MAX_WAIT_TIME = 30000L // 最大等待时间30秒
    private val CHECK_INTERVAL = 500L // 检查间隔500毫秒
    
    // 数据读取状态相关变量
    private var isDataReading = false
    private var isDataReadComplete = false
    
    // 更新检测相关变量
    private var mObdResource: ObdResource? = null
    private var mVciFirmwareResource: VciFirmwareResource? = null
    private var updateCheckComplete = false
    private var hasUpdateAvailable = false
    private var isVerifyingUpdate = false // 标记是否正在验证更新
    private var isFromUpdatePage = false // 标记是否从更新页面返回
    
    fun updateImageList(data: Intent?) {
        if (data != null) {
            val uri: Uri? = data.getData()

            if (uri != null){
                adapter.addImage(uri) // 这里会触发 OnPhotoTakenListener 回调
                Log.i(TAG, "scanProgress "+ uri);
                val realPath = getRealPathFromUri(uri);
                
                // 检查路径是否有效
                if (realPath.isNullOrEmpty()) {
                    Log.e(TAG, "无法获取文件路径: $uri")
                    Toast.makeText(context, "无法获取文件路径", Toast.LENGTH_SHORT).show()
                    return
                }
                
                val file = File(realPath)
                Log.i(TAG, "scanProgress "+ file);
                
                // 检查文件是否存在
                if (!file.exists()) {
                    Log.e(TAG, "文件不存在: $realPath")
                    Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show()
                    return
                }
                
                httpUtil.postFileRequest("http://115.153.96.26:10061/api/upload/single", file, object :
                    StringCallback() {
                    override fun onError(call: Call?, e: Exception?, id: Int) {
                        Log.e(TAG, "上传失败: ${e?.message}")
                        Toast.makeText(context, "拍照成功但上传失败: ${e?.message}", Toast.LENGTH_SHORT).show()
                        // 上传失败时才删除文件
                        if (file.exists()) {
                            file.delete()
                        }
                    }

                    override fun onResponse(response: String?, id: Int) {
                        if (response != null) {
                            Log.i(TAG, "上传响应: $response")
                            try {
                                val uploadResponse = Gson().fromJson(response, UploadResponse::class.java)
                                if (uploadResponse.code == 200) {
                                    Log.i(TAG, "上传成功: ${uploadResponse.data}")
                                    uploadImageList.add(uploadResponse.data)
                                    Toast.makeText(context, "拍照并上传成功", Toast.LENGTH_SHORT).show()
                                } else {
                                    Log.e(TAG, "上传失败，服务器返回: $response")
                                    Toast.makeText(context, "拍照成功但上传失败: ${uploadResponse.data}", Toast.LENGTH_SHORT).show()
                                }
                            } catch (e: Exception) {
                                Log.e(TAG, "解析响应失败: ${e.message}")
                                Toast.makeText(context, "解析响应失败", Toast.LENGTH_SHORT).show()
                            }
                        }
                        // 上传完成后删除临时文件
                        if (file.exists()) {
                            file.delete()
                        }
                    }
                })
            }
        }
    }

    private fun getRealPathFromUri(uri: Uri): String? {
        return try {
            when (uri.scheme) {
                "file" -> {
                    Log.d(TAG, "File URI: ${uri.path}")
                    uri.path
                }
                "content" -> {
                    Log.d(TAG, "Content URI: $uri")
                    // 处理ContentResolver获取路径
                    val cursor = context?.contentResolver?.query(
                        uri, 
                        arrayOf(MediaStore.MediaColumns.DATA), 
                        null, null, null
                    )
                    cursor?.use {
                        if (it.moveToFirst()) {
                            val path = it.getString(0)
                            Log.d(TAG, "Content path: $path")
                            path
                        } else {
                            Log.w(TAG, "Cursor is empty")
                            null
                        }
                    }
                }
                else -> {
                    Log.w(TAG, "Unknown URI scheme: ${uri.scheme}")
                    null
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error getting real path from URI: ${e.message}")
            null
        }
    }

    // 创建旋转提示对话框
    private fun createLoadingDialog(message: String = "正在读取数据，请稍候..."): Dialog {
        val dialog = Dialog(requireContext())
        dialog.setContentView(R.layout.dialog_loading)
        dialog.setCancelable(false)
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        
        val messageText = dialog.findViewById<TextView>(R.id.tv_loading_message)
        messageText?.text = message
        
        return dialog
    }
    
    // 显示旋转提示对话框
    private fun showLoadingDialog(message: String = "正在读取数据，请稍候...") {
        hideLoadingDialog()
        loadingDialog = createLoadingDialog(message)
        loadingDialog?.show()
    }
    
    // 隐藏旋转提示对话框
    private fun hideLoadingDialog() {
        loadingDialog?.dismiss()
        loadingDialog = null
    }
    
    // 开始检查数据
    private fun startDataCheck(checkType: String, onDataReady: () -> Unit) {
        showLoadingDialog("正在读取${checkType}，请稍候...")
        
        dataCheckHandler = Handler(Looper.getMainLooper())
        val startTime = System.currentTimeMillis()
        
        dataCheckRunnable = object : Runnable {
            override fun run() {
                val currentTime = System.currentTimeMillis()
                val elapsedTime = currentTime - startTime
                
                // 检查是否有数据
                val hasData = when (checkType) {
                    "数据流" -> realTimeItems.isNotEmpty()
                    "故障码" -> Singleton.getObdDetector().dtc.isNotEmpty()
                    else -> false
                }
                
                if (hasData) {
                    // 有数据了，停止检查并执行回调
                    hideLoadingDialog()
                    stopDataCheck()
                    onDataReady()
                } else if (elapsedTime >= MAX_WAIT_TIME) {
                    // 超时了，停止检查并提示
                    hideLoadingDialog()
                    stopDataCheck()
                    Toast.makeText(requireContext(), "读取${checkType}超时，请稍后重试", Toast.LENGTH_LONG).show()
                } else {
                    // 继续检查
                    dataCheckHandler?.postDelayed(this, CHECK_INTERVAL)
                }
            }
        }
        
        dataCheckHandler?.post(dataCheckRunnable!!)
    }
    
    // 停止检查数据
    private fun stopDataCheck() {
        dataCheckRunnable?.let { 
            dataCheckHandler?.removeCallbacks(it)
        }
        dataCheckRunnable = null
        dataCheckHandler = null
    }
    
    // 检查并显示数据读取对话框
    private fun checkAndShowDataReadingDialog() {
        // 如果数据已经读取完成，不显示提示
        if (isDataReadComplete) {
            return
        }
        
        // 先检测更新，再检查数据流
        if (!updateCheckComplete) {
            checkForUpdates()
        } else {
            // 更新检测完成，检查数据流
            checkDataStreamAfterUpdate()
        }
    }
    
    // 检测更新
    private fun checkForUpdates() {
        Log.i(TAG, "开始检测程序更新...")
        showLoadingDialog("正在检测程序更新，请稍候...")
        
        // 初始化资源管理器
        mObdResource = ObdResource.getInstance()
        mVciFirmwareResource = VciFirmwareResource.getInstance()
        
        // 检测OBD诊断程序更新
        checkObdResourceUpdate()
    }
    
    // 检测OBD诊断程序更新
    private fun checkObdResourceUpdate() {
        mObdResource?.isHaveNew(requireContext()) { resultCode ->
            when (resultCode) {
                HttpRespondCode.RESPOND_UPDATE_YES -> {
                    Log.i(TAG, "OBD诊断程序: 有更新")
                    hasUpdateAvailable = true
                    checkVciFirmwareUpdate()
                }
                HttpRespondCode.RESPOND_UPDATE_NO -> {
                    Log.i(TAG, "OBD诊断程序: 无更新")
                    checkVciFirmwareUpdate()
                }
                HttpRespondCode.RESPOND_NETWORK_NONE -> {
                    Log.i(TAG, "OBD诊断程序: 无网络连接")
                    checkVciFirmwareUpdate()
                }
                else -> {
                    Log.i(TAG, "OBD诊断程序: 检测失败，错误代码: $resultCode")
                    checkVciFirmwareUpdate()
                }
            }
        }
    }
    
    // 检测VCL固件更新
    private fun checkVciFirmwareUpdate() {
        mVciFirmwareResource?.isHaveNew(requireContext()) { resultCode ->
            when (resultCode) {
                HttpRespondCode.RESPOND_UPDATE_YES -> {
                    Log.i(TAG, "VCL固件: 有更新")
                    hasUpdateAvailable = true
                    checkDiagnosticLibraryUpdate()
                }
                HttpRespondCode.RESPOND_UPDATE_NO -> {
                    Log.i(TAG, "VCL固件: 无更新")
                    checkDiagnosticLibraryUpdate()
                }
                HttpRespondCode.RESPOND_NETWORK_NONE -> {
                    Log.i(TAG, "VCL固件: 无网络连接")
                    checkDiagnosticLibraryUpdate()
                }
                else -> {
                    Log.i(TAG, "VCL固件: 检测失败，错误代码: $resultCode")
                    checkDiagnosticLibraryUpdate()
                }
            }
        }
    }
    
    // 检测诊断基础库更新
    private fun checkDiagnosticLibraryUpdate() {
        VinUtils.checkOBDSDKVINUpdate { resultCode ->
            when (resultCode) {
                HttpRespondCode.RESPOND_UPDATE_YES -> {
                    Log.i(TAG, "诊断基础库: 有更新")
                    hasUpdateAvailable = true
                    finishUpdateCheck()
                }
                HttpRespondCode.RESPOND_UPDATE_NO -> {
                    Log.i(TAG, "诊断基础库: 无更新")
                    finishUpdateCheck()
                }
                HttpRespondCode.RESPOND_NETWORK_NONE -> {
                    Log.i(TAG, "诊断基础库: 无网络连接")
                    finishUpdateCheck()
                }
                else -> {
                    Log.i(TAG, "诊断基础库: 检测失败，错误代码: $resultCode")
                    finishUpdateCheck()
                }
            }
        }
    }
    
    // 完成更新检测
    private fun finishUpdateCheck() {
        updateCheckComplete = true
        
        if (hasUpdateAvailable) {
            // 有更新，跳转到更新页面
            hideLoadingDialog()
            showUpdateDialog()
        } else {
            // 无更新，继续检查数据流
            if (isVerifyingUpdate) {
                Log.i(TAG, "更新验证完成，无更新，开始检查数据流")
                isVerifyingUpdate = false
                hideLoadingDialog() // 确保隐藏验证对话框
            } else {
                Log.i(TAG, "更新检测完成，无更新，开始检查数据流")
            }
            checkDataStreamAfterUpdate()
        }
    }
    
    // 验证更新是否完成（从更新页面返回后调用）
    private fun verifyUpdateCompletion() {
        Log.i(TAG, "验证更新是否完成...")
        isVerifyingUpdate = true
        showLoadingDialog("正在验证更新状态，请稍候...")
        
        // 设置超时机制，防止验证卡住
        Handler(Looper.getMainLooper()).postDelayed({
            if (isVerifyingUpdate) {
                Log.w(TAG, "验证更新超时，强制完成")
                isVerifyingUpdate = false
                hideLoadingDialog()
                checkDataStreamAfterUpdate()
            }
        }, 10000) // 10秒超时
        
        // 重新检测所有更新，确认是否还有更新
        hasUpdateAvailable = false
        checkObdResourceUpdate()
    }
    
    // 显示更新对话框
    private fun showUpdateDialog() {
        AlertDialog.Builder(requireContext())
            .setTitle("程序更新")
            .setMessage("检测到程序有更新，是否前往更新页面？")
            .setPositiveButton("前往更新") { _, _ ->
                // 跳转到更新页面
                isFromUpdatePage = true // 标记从更新页面跳转
                val intent = Intent(requireContext(), UpdateActivity::class.java)
                startActivity(intent)
            }
            .setNegativeButton("稍后更新") { _, _ ->
                // 用户选择稍后更新，继续检查数据流
                isFromUpdatePage = false // 标记不是从更新页面返回
                checkDataStreamAfterUpdate()
            }
            .setCancelable(false)
            .show()
    }
    
    // 更新检测完成后检查数据流
    private fun checkDataStreamAfterUpdate() {
        // 检查是否有数据流
        if (realTimeItems.isEmpty()) {
            // 没有数据，显示数据读取提示
            showDataReadingDialog()
            isDataReading = true
        }
    }
    
    // 重置更新检测状态
    private fun resetUpdateStatus() {
        updateCheckComplete = false
        hasUpdateAvailable = false
        isDataReading = false
        isDataReadComplete = false
        isVerifyingUpdate = false
        isFromUpdatePage = false
        Log.i(TAG, "重置更新检测状态")
    }
    
    // 显示数据读取对话框
    private fun showDataReadingDialog() {
        showLoadingDialog("正在读取数据流，请稍候...")
    }
    
    // 隐藏数据读取对话框
    private fun hideDataReadingDialog() {
        hideLoadingDialog()
        isDataReading = false
        isDataReadComplete = true
    }
    
    // 更新扫描进度（从MainActivity2调用）
    fun updateScanProgress(currentTask: String?, progress: Int) {
        Log.i(TAG, "updateScanProgress: currentTask: $currentTask, progress: $progress")
        
        // 检查是否是数据读取完成
        if (currentTask == "数据读取完成" && progress == 100) {
            // 数据读取完成，隐藏提示
            if (isDataReading) {
                hideDataReadingDialog()
                Toast.makeText(requireContext(), "数据读取完成", Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun previewImage(uri: Uri) {
        val builder = AlertDialog.Builder(requireActivity())
        builder.setView(layoutInflater.inflate(R.layout.image_preview, null))
        val dialog = builder.create();
        dialog.show()

        val photoView = dialog.findViewById<PhotoView>(R.id.photo_view)
        Glide.with(requireActivity()).load(uri).into(photoView)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 清理资源
        stopDataCheck()
        hideLoadingDialog()
    }

    companion object {
         const val CAMERA_IMAGE_REQ_CODE = 101;
    }
}